// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
import * as path from 'path';
import * as request from 'request';
import * as fs from 'fs';

// 伪装成浏览器，解决2cto.com的403错误
const headers = { "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36" };
const options = { strictSSL: false, headers };
// 同步下载方法封装
function download(url: string, filePath: string) {
	return new Promise(function (resolve, reject) {
		var stream = request(url, options)
			.on('error', (e: any) => {
				reject(e);
			})
			.pipe(
				fs.createWriteStream(filePath)
			);
		stream.on('finish', function () {
			resolve({ url, filePath });
		});
	});
}

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {
	// 编辑器命令
	context.subscriptions.push(vscode.commands.registerTextEditorCommand('download-image-in-markdown.downloadImage', async (textEditor: vscode.TextEditor, edit: vscode.TextEditorEdit, uri: any) => {
		const dir = path.dirname(uri.fsPath);
		let imagePath: string = vscode.workspace.getConfiguration().get('downloadImageInMarkdown.imageSaveFolder') || '.';
		const isAsync: boolean = vscode.workspace.getConfiguration().get('downloadImageInMarkdown.isAsync') as boolean;

		if (imagePath.endsWith('/')) {
			imagePath = imagePath.substr(0, imagePath.length - 1);
		}

		const dir2 = path.resolve(dir, imagePath);

		let text = textEditor.document.getText();
		const allImages = text.match(/!\[.*?\]\((http[s]{0,1}.*?)\)/g) || [];
		const timeStamp = new Date().getTime();
		if (allImages.length > 0) {
			const df = async () => {
				for (let i = 0; i < allImages.length; i++) {
					const r = /!\[.*?\]\((http[s]{0,1}.*?)\)/g.exec(allImages[i]);
					const url = r![1];

					const fileName = `${timeStamp}-${i}.png`;
					const relFileName = `${imagePath}/${fileName}`;

					const dest = `${dir2}/${fileName}`;

					try {
						if (isAsync) {
							request(url, options)
								.pipe(fs.createWriteStream(dest));
						}
						else {
							await download(url, dest);
						}

						text = text.replace(url, relFileName);
					}
					catch (e) {
						console.log('errors:', e);
					}
				}
				textEditor.edit((editBuilder: vscode.TextEditorEdit) => {
					const end = new vscode.Position(textEditor.document.lineCount + 1, 0);
					editBuilder.replace(new vscode.Range(new vscode.Position(0, 0), end), text);
				});
			};
			if (isAsync) {
				df();
				vscode.window.showInformationMessage("已经启动后台下载图片");
			} else {
				await vscode.window.withProgress({
					title: '网络图片正在下载到本地',
					location: vscode.ProgressLocation.Notification
				}, async () => {
					await df();
				});
			}
		}
		else {
			vscode.window.showInformationMessage("Markdown中不包含要下载的网络图片");
		}
	}));

}

// this method is called when your extension is deactivated
export function deactivate() { }
